import React, { useContext } from "react";
import { View, StyleSheet, Dimensions, Text, Image, TouchableOpacity, ScrollView } from "react-native";
import { Icon } from "@rneui/themed";
import NoListImg from '@/assets/safe/no_list.png'
import CommonContext from '@/utils/createContext'
import { TranscationType } from '@/config/config'
import moment from "moment";
import { getTransactionType, getTransactionAmount } from "@/utils/util";

const { width, height, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const HistoryList = () => {

    const { safeHistoryList, handlePressItem, handlePressCreation, loadMore } = useContext(CommonContext)

    // 定义分组中的每个单元格
    const listRow = (transaction) => {
        const typeData = getTransactionType(transaction) || {}
        const amountData = getTransactionAmount(transaction.txInfo) || {}
        const type = transaction.txInfo.type === 'Custom' && transaction.txInfo.isCancellation ? 'rejection' :
            transaction.txInfo.type === 'Transfer' && transaction.txInfo.direction === 'OUTGOING' ? 'general' : 'receive'
        return (
            <View key={transaction.id} style={styles.sectionItem}>
                <View style={{ flex: 6, height: 60 * ratio, marginTop: 3 * ratio }}>
                    <View style={{ flexDirection: 'row', marginLeft: 19 * ratio, alignItems: 'center' }}>
                        <Image source={TranscationType[typeData.icon]} style={{ width: typeData.size * ratio, height: typeData.size * ratio, marginTop: 3 * ratio }} />
                        <Text style={{ ...styles.title1, marginLeft: 6 * ratio }}>{typeData.text}</Text>
                    </View>
                    <View style={{ flexDirection: 'row', marginLeft: 19 * ratio, marginTop: 9 * ratio }}>
                        <Text style={styles.title2}>{moment(transaction.timestamp).format('HH:mm')}</Text>
                        <Text style={{ ...styles.title2, color: '#0A6EEB', marginLeft: 5 * ratio }}>{transaction.txStatus}</Text>
                    </View>
                </View>
                <TouchableOpacity onPress={() => handlePressItem(transaction.id, type)}
                    style={{ flex: 4, height: 60 * ratio, flexDirection: 'row', justifyContent: 'flex-end' }}>
                    <View>
                        <Text style={{ ...styles.title1, marginRight: 10 * ratio, color: typeData.text === 'Received' ? '#0B6FEB' : '#2C2C2C' }}>
                            {amountData.directionSign} {amountData.amountWithSymbol}
                        </Text>
                    </View>
                    <View style={{ alignItems: 'flex-end', justifyContent: 'center' }} >
                        <Icon style={{ marginRight: 16 * ratio }} type="antdesign" size={13}
                            color='#000000' name='right' />
                    </View>
                </TouchableOpacity>
            </View>
        )
    };

    const listCreationRow = (transaction) => {
        return (
            <View key={transaction.id} style={styles.sectionItem}>
                <View style={{ flex: 8, height: 60 * ratio, marginTop: 3 * ratio }}>
                    <View style={{ flexDirection: 'row', marginLeft: 19 * ratio, alignItems: 'center' }}>
                        <Image source={require('@/assets/safe/setting.png')} style={{ width: 12 * ratio, height: 12 * ratio, marginTop: 3 * ratio }} />
                        <Text style={{ ...styles.title1, marginLeft: 6 * ratio }}>Safe created</Text>
                    </View>
                    <View style={{ flexDirection: 'row', marginLeft: 19 * ratio, marginTop: 9 * ratio }}>
                        <Text style={styles.title2}>{moment(transaction.timestamp).format('HH:mm')}</Text>
                        <Text style={{ ...styles.title2, color: '#0A6EEB', marginLeft: 5 * ratio }}>{transaction.txStatus}</Text>
                    </View>
                </View>
                <TouchableOpacity style={{ flex: 2, height: 60 * ratio, alignItems: 'flex-end', justifyContent: 'center' }}
                    onPress={() => handlePressCreation(transaction)}>
                    <Icon style={{ marginRight: 16 * ratio }} type="antdesign" size={13}
                        color='#000000' name='right' />
                </TouchableOpacity>
            </View>
        )
    };

    //上拉加载数据,如果有的话
    const onMomentumScrollEnd = (event) => {
        const offSetY = event.nativeEvent.contentOffset.y; // 获取滑动的距离
        const contentSizeHeight = event.nativeEvent.contentSize.height; // scrollView  contentSize 高度
        const oriageScrollHeight = event.nativeEvent.layoutMeasurement.height; // scrollView高度
        if (offSetY + oriageScrollHeight >= contentSizeHeight - 1) {
            //加载新数据
            loadMore('history')
        }
    }

    return (
        <ScrollView style={styles.container}
            onScrollEndDrag={onMomentumScrollEnd}>
            {safeHistoryList && safeHistoryList.length > 0 ?
                safeHistoryList.map(([timestamp, txs], index) => {
                    return (
                        <View key={index}>
                            <View style={styles.sectionHeader}>
                                <Text style={{ ...styles.title2, color: '#616161', marginLeft: 15 * ratio }}>
                                    {moment(Number(timestamp)).format('MMM DD, YYYY')}
                                </Text>
                            </View>
                            <View>
                                {txs.map((transaction) => {
                                    return transaction.txInfo.type === 'Creation' ? listCreationRow(transaction) : listRow(transaction)
                                })}
                            </View>
                        </View>
                    )
                })
                :
                <View style={styles.noListContent}>
                    <Image source={NoListImg} style={{ width: 120 * ratio, height: 100 * ratio }} />
                    <Text style={{ ...styles.title1, marginTop: 15 * ratio }}>Transactions will appear here</Text>
                </View>}
        </ScrollView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    bodyContent: {
        flex: 1
    },
    noListContent: {
        width: width,
        height: height * 0.6,
        justifyContent: 'center',
        alignItems: 'center'
    },
    title1: {
        fontSize: 14,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#2C2C2C',
        lineHeight: 20
    },
    title2: {
        fontSize: 12,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#898989',
        lineHeight: 18
    },
    sectionHeader: {
        width: width,
        height: 44 * ratio,
        backgroundColor: '#F5F5F5',
        justifyContent: 'center'
    },
    sectionItem: {
        width: width,
        height: 60 * ratio,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottomColor: '#EFEFEF',
        borderBottomWidth: 1
    },
    divider: {
        width: width,
        height: 1,
        backgroundColor: '#EFEFEF'
    }
})
export default HistoryList